package com.example.myapplication5.viewmodel

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myapplication5.entity.Todo
import com.example.myapplication5.service.TodoDao
import com.example.myapplication5.service.TodoService
import com.example.myapplication5.utils.RandomUtil
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class EditorViewModel(dao: TodoDao):ViewModel() {
    var todo by mutableStateOf(Todo())
        private set
    //toast 内容
    private val toastContent= MutableSharedFlow<String>()
    val toast=toastContent.asSharedFlow()

    private val service=TodoService(dao)

    //时间格式
    private val dateFormat=SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.CHINA)
    fun onValueChange(content:String){
        todo=todo.copy(content=content)
    }

    fun onSave(){
        viewModelScope.launch {
            if (todo.id.trim()==""){
                todo.date=dateFormat.format(Date())
                todo.id=RandomUtil.randomString()
                service.insert(todo)
            }else{
                service.update(todo)
            }

            toastContent.emit("保存成功")
        }
    }

    fun fetch(id:String){
        viewModelScope.launch {
            if (id!=""&&!id.equals("0")){
               todo= service.loadById(id)
            }
        }

    }
}